package com.gdut.multiusercommunicationsystem.controller;

import com.gdut.multiusercommunicationsystem.model.User;
import com.gdut.multiusercommunicationsystem.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {
    @Resource
    UserService userService;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest httpServletRequest){
        //登录
        User user=userService.getUserByName(username);
        if(user==null || !user.getPassword().equals(password)){
            //没有这个用户，或者密码错误
            System.out.println("没有这个用户，或者密码错误");
            return new User();
        }
        //验证通过,设置sessionID，返回对象
        HttpSession httpSession=httpServletRequest.getSession(true);
        httpSession.setAttribute("user",user);
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username,String password){
        //注册
        //先从数据库中找找有没有这个用户
        User user=null;
        try {
            user=new User();
            user.setUsername(username);
            user.setPassword(password);
            userService.insert(user);
            user.setPassword("");
        } catch (DuplicateKeyException e) {
            user=new User();
            System.out.println("注册失败!");
        }
        return user;
    }

    @GetMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest httpServletRequest){
        HttpSession httpSession=httpServletRequest.getSession(false);
        if(httpSession==null){
            System.out.println("未创建会话");
            return new User();
        }
        User user=(User) httpSession.getAttribute("user");
        if(user==null){
            System.out.println("用户不存在");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
